﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace ICeFramework.Serialization
{
    public static class XmlSerialization
    {
        #region public static object FromXML(string xmlString, Type objectType)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlString"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public static object FromXML(string xmlString, Type objectType)
        {
            XmlSerializer resultSerializer = new XmlSerializer(objectType);

            if (resultSerializer != null)
            {
                MemoryStream ms = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(xmlString));
                ms.Position = 0;

                object obj = resultSerializer.Deserialize(ms);

                ms.Close();
                ms.Dispose();
                return obj;
            }
            return null;
        }
        #endregion

        #region public static string ToXML(object objectInstance)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objectInstance"></param>
        /// <returns></returns>
        public static string ToXML(object objectInstance)
        {
            XmlSerializer resultSerializer = new XmlSerializer(objectInstance.GetType());

            if (resultSerializer != null)
            {
                StringBuilder resultBuilder = new StringBuilder();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.IndentChars = ("    ");
                settings.Encoding = Encoding.UTF8;
                settings.OmitXmlDeclaration = true;
                XmlWriter writer = XmlTextWriter.Create(resultBuilder, settings);

                resultSerializer.Serialize(writer, objectInstance);
                writer.Flush();
                writer.Close();
                return resultBuilder.ToString();
            }
            return null;
        }
        #endregion
    }
}
